package com.itheima.zhaohang.threechenge;

import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private EditText    mEditText;
    private ListView    mOneList;
    private ListView    mTwolist;
    private ListView    mThreelist;
    private PopupWindow mPopupWindow;
    private Button      mButton;
    //省份的数据集合
    private List<AreaBeen> proviesList     = new ArrayList<>();
    private int            proviesPosition = -1;

    //城市的
    private List<AreaBeen> cityList     = new ArrayList<>();
    private int            cityPosition = -1;
    //地区的
    private List<AreaBeen> areaList     = new ArrayList<>();
    private int            arePosition  = -1;
    private File        mFile;
    private MenuAdapter mAdapter;
    private String      mName;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            //初始化adapter
            initListViewAdapter();
            initToDo();
        }
    };
    private MenuAdapter mCityAdapter;
    private String      mName1;
    private MenuAdapter areaAdapter;

    private void initToDo() {

        mOneList.setOnItemClickListener(this);
        mTwolist.setOnItemClickListener(this);
        mThreelist.setOnItemClickListener(this);

    }

    private String provice = "";
    private String city = "";
    private String are = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEditText = (EditText) findViewById(R.id.edit_text);
        mButton = (Button) findViewById(R.id.button);


        new Thread(new Runnable() {
            @Override
            public void run() {
                //读取数据库
                initData();
                //读取数据库中省份的数据
                initReadSQL();
                mHandler.sendEmptyMessage(0);
            }
        }).start();

        //创建popupwindow
        initPopupwindow();


    }

    private void initReadSQL() {
        //从本地数据库中读取数据
        SQLiteDatabase database = SQLiteDatabase.openDatabase(mFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = database.rawQuery("select code,name from province", null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                //                乱码解决问题

                byte[] blob = cursor.getBlob(1);
                try {
                    mName = new String(blob, "gbk");

                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();
                }


                //                String name = cursor.getString(1);
                AreaBeen been = new AreaBeen();
                been.name = mName;
                been.code = code;
                proviesList.add(been);

            }

        }
        cursor.close();

        database.close();

    }

    private void initListViewAdapter() {

        if (mAdapter == null) {
            mAdapter = new MenuAdapter(MainActivity.this, proviesList);
            mOneList.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }


    }

    private void initPopupwindow() {
        View popupView = View.inflate(MainActivity.this, R.layout.view_popupwidow, null);
        mOneList = (ListView) popupView.findViewById(R.id.onelist);
        mTwolist = (ListView) popupView.findViewById(R.id.twolist);
        mThreelist = (ListView) popupView.findViewById(R.id.threelist);

        mPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //设置外部点击可取消
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());


    }

    private void initData() {
        //将外部数据库复制到data/data/包名/file
        mFile = new File(getFilesDir(), "city.db");
        //如果文件已经存在了，就要不用复制了
        if (mFile.exists()) {
            return;
        }

        //方式一
        AssetManager assets = getAssets();

        InputStream mOpen = null;
        FileOutputStream mOutputStream = null;
        try {
            //读出的都是流
            mOpen = assets.open("db/city.s3db");
            mOutputStream = new FileOutputStream(mFile);
            byte[] buffer = new byte[1024];
            int b = -1;
            while ((b = mOpen.read(buffer)) != -1) {

                mOutputStream.write(buffer, 0, b);
            }

            mOutputStream.flush();


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (mOpen != null) {

                try {
                    mOpen.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //方式二
        //读出的都是流
        //        InputStream stream = getResources().openRawResource(R.raw.city);

    }

    public void onclick(View view) {
        mPopupWindow.showAsDropDown(mButton);

    }

    /**
     * 条目点击事件
     *
     * @param adapterView
     * @param view
     * @param i
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        switch (adapterView.getId()) {
            case R.id.onelist:
                //                存在复用问题
                //                view.setBackgroundResource(R.mipmap.choose_item_selected);


                if (proviesPosition != -1 && proviesPosition != i) {
                    proviesList.get(proviesPosition).isSclect = false;
                }
                proviesPosition = i;


                AreaBeen proviceBeen = (AreaBeen) adapterView.getItemAtPosition(i);


                //防止点击同一个条目的时候进行不停的刷新
                if (!proviceBeen.isSclect) {
                    proviceBeen.isSclect = true;

                    mAdapter.notifyDataSetChanged();
                }
                //根据省份的code初始化city
                initCityByProvice(proviceBeen);
                //为了防止索引越界,避免不同的cityList长度不同造成越界
                cityPosition = -1;

                //处理细节问题
                if (areaAdapter!=null){
                    areaList.clear();
                    areaAdapter.notifyDataSetChanged();

                }

                provice = proviceBeen.name;

                mEditText.setText(provice);
                break;
            case R.id.twolist:


                if (cityPosition != -1 && cityPosition != i) {
                    cityList.get(cityPosition).isSclect = false;
                }
                cityPosition = i;


                AreaBeen cityBeen = (AreaBeen) adapterView.getItemAtPosition(i);


                //防止点击同一个条目的时候进行不停的刷新
                if (!cityBeen.isSclect) {
                    cityBeen.isSclect = true;

                    mCityAdapter.notifyDataSetChanged();
                }
                //根据市区的code初始化地区area
                initAreaByCity(cityBeen);
                arePosition = -1;
                city = cityBeen.name;
                mEditText.setText(provice+"   "+city);
                break;
            case R.id.threelist:

                if (arePosition != -1 && arePosition != i) {
                    areaList.get(arePosition).isSclect = false;
                }
                arePosition = i;


                AreaBeen areaBeen = (AreaBeen) adapterView.getItemAtPosition(i);


                //防止点击同一个条目的时候进行不停的刷新
                if (!areaBeen.isSclect) {
                    areaBeen.isSclect = true;

                    areaAdapter.notifyDataSetChanged();
                }
                are = areaBeen.name;
                mEditText.setText(provice+"   "+city+"    "+are);


                break;
        }

    }

    private void initAreaByCity(AreaBeen cityBeen) {
        //从城市中选中地区
        readDataByCity(cityBeen);

        if (areaAdapter == null) {
            areaAdapter = new MenuAdapter(MainActivity.this, areaList);
            mThreelist.setAdapter(areaAdapter);
        } else {
            areaAdapter.notifyDataSetChanged();
        }


    }

    private void readDataByCity(AreaBeen cityBeen) {
        if (areaList != null) {
            areaList.clear();
        }

        SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(mFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = sqLiteDatabase.rawQuery("select code,name from district where pcode = ?", new String[]{cityBeen.code});
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                //                乱码解决问题

                byte[] blob = cursor.getBlob(1);
                try {
                    mName1 = new String(blob, "gbk");

                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();
                }


                //                String name = cursor.getString(1);
                AreaBeen been = new AreaBeen();
                been.name = mName1;
                been.code = code;
                areaList.add(been);

            }

        }
        cursor.close();

        sqLiteDatabase.close();





    }

    //根据省份初始化城市列表
    private void initCityByProvice(AreaBeen proviceBeen) {

        //根据省获取市
        readDataByProvice(proviceBeen);

        if (mCityAdapter == null) {

            mCityAdapter = new MenuAdapter(MainActivity.this, cityList);
            mTwolist.setAdapter(mCityAdapter);
        } else {
            mCityAdapter.notifyDataSetChanged();
        }

    }

    private void readDataByProvice(AreaBeen proviceBeen) {
        if (cityList != null) {
            cityList.clear();
        }

        SQLiteDatabase sqLiteDatabase = SQLiteDatabase.openDatabase(mFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = sqLiteDatabase.rawQuery("select code,name from city where pcode = ?", new String[]{proviceBeen.code});
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String code = cursor.getString(0);
                //                乱码解决问题

                byte[] blob = cursor.getBlob(1);
                try {
                    mName1 = new String(blob, "gbk");

                } catch (UnsupportedEncodingException e) {

                    e.printStackTrace();
                }


                //                String name = cursor.getString(1);
                AreaBeen been = new AreaBeen();
                been.name = mName1;
                been.code = code;
                cityList.add(been);

            }

        }
        cursor.close();

        sqLiteDatabase.close();


    }
}
